#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include "StdUdp.h"

struct StdUdpServer
{
    int sock;
    char Ip[20];
    short port;
};

UdpS *InitUdpServer(const char *ip, short port)
{
    UdpS *s=(UdpS*)malloc(sizeof(UdpS));
    if(s==NULL)
    {
        printf("InitUdpServer malloc error!\n");
        return NULL;
    }
    s->sock=socket(AF_INET,SOCK_DGRAM,0);
    if(s->sock<0)
    {
        perror("udp socket:");
        free(s);
        return NULL;
    }

    s->port=port;
    strcpy(s->Ip,ip);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(s->port);
    addr.sin_addr.s_addr = inet_addr(s->Ip);   

    if(bind(s->sock,(struct socketaddr*)&addr,sizeof(addr))<0)
    {
        perror("udp bind:");
        free(s);
        return NULL;
    }
    return s;
}

void UdpServerSend(UdpS *s,const char *destIp, const short destPort, void *ptr, size_t size)
{
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        perror("socket:");
        return;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(destPort);
    addr.sin_addr.s_addr = inet_addr(destIp);
    
    if(sendto(s->sock,ptr,size,0,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    {
        perror("UdpServerSend sendto:");
    }
}

void UdpServerRecv(UdpS *s,void *ptr, size_t size)
{
    struct sockaddr_in clientAddr;
    socklen_t len;
    if(recvfrom(s->sock,ptr,size,0,(struct sockaddr*)&clientAddr,&len) <= 0)
    {
        perror("UdpServerRecv recvfrom:");
    } 
}

void CloseServer(UdpS *s)
{
    close(s->sock);
    free(s);
}

struct StdUdpClient
{
    int sock;
    char Ip[20];
    short port;
};

UdpC *InitUdpClient(const char *serverIp, const short port)
{
    UdpC *c=(UdpC*)malloc(sizeof(UdpC));
    if(c==NULL)
    {
        printf("InitUdpClient malloc error!\n");
        return NULL;
    }   
    c->sock=socket(AF_INET,SOCK_DGRAM,0);
    if(c->sock<0)
    {
        perror("InitUdpClient socket:");
        free(c);
        return NULL;
    }
    strcpy(c->Ip,serverIp);
    c->port=port;
    return c;
}

void UdpClientSend(UdpC *c, void *ptr, size_t size)
{
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(c->port);
    addr.sin_addr.s_addr = inet_addr(c->Ip);
    
    if(sendto(c->sock,ptr,size,0,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    {
        perror("UdpClientSend sendto:");
    }
}

void UdpClientRecv(UdpC *c, void *ptr, size_t size)
{
    struct sockaddr_in clientAddr;
    socklen_t len;
    if(recvfrom(c->sock,ptr,size,0,(struct sockaddr*)&clientAddr,&len) <= 0)
    {
        perror("UdpClientRecv recvfrom:");
    }     
}

void CloseClient(UdpC *c)
{
    close(c->sock);
    free(c);
}


